﻿using CSRedis;
using Microsoft.Extensions.Caching.Distributed;
//using Microsoft.Extensions.Caching.Redis;
using Newtonsoft.Json;
//using StackExchange.Redis;
using System;
using System.Collections.Generic;
using System.Threading.Tasks;

namespace Hu.Smart.Core.Redis
{
    public class RedisCacheHelper
    {
       // private static RedisCache _redisCache = null;
        //private static RedisCacheOptions options = null;
        private static CSRedisClient _csredis = null;
        /// <summary>
        ///
        /// </summary>
        /// <param name="connectionString"></param>
        /// <param name="instanceName"></param>
        public RedisCacheHelper(string connectionString, string instanceName)
        {
            //options = new RedisCacheOptions();
            //options.Configuration = connectionString;
            //options.InstanceName = instanceName;
            //_redisCache = new RedisCache(options);
        }


        /// <summary>
        /// 初始化Redis
        /// </summary>
        public static void InitRedis(string connectionString, string instanceName)
        {
            //options = new RedisCacheOptions();
            //options.Configuration = connectionString;
            //options.InstanceName = instanceName;
            //_redisCache = new RedisCache(options);
        }

        /// <summary>
        /// 创建哨兵模式连接
        /// </summary>
        /// <param name="connectionString"></param>
        /// <param name="guards"></param>
        public static void InitGuardRedis(string connectionString, List<string> guards)
        {
            if (_csredis == null)
            {
                var csredis = new CSRedis.CSRedisClient($"{connectionString}, prefix=my_", guards.ToArray());
                _csredis = csredis;
            }
        }

        public static string[] GetAllKeys()
        {
           var keys=  _csredis.Scan(0);
           if(keys.Items.Length != 0)
           {
               return keys.Items;
           }
           return new string[0]; 
        }
        /// <summary>
        /// 添加string数据
        /// </summary>
        /// <param name="key">键</param>
        /// <param name="value">值</param>
        /// <param name="ExprireTime">过期时间 单位分钟  默认缓存1小时</param>
        /// <returns></returns>
        public static bool SetStringValue(string key, string value, int ExprireTime = 20)
        {
            if (string.IsNullOrEmpty(key))
            {
                return false;
            }
            try
            {
                _csredis.Set(key, value, ExprireTime * 60);
                //_redisCache.SetString(key, value, new DistributedCacheEntryOptions()
                //{
                //    AbsoluteExpiration = DateTime.Now.AddHours(ExprireTime)
                //});
                return true;
            }
            catch (Exception ex)
            {
                return false;
            }
        }
        /// <summary>
        /// 获取string数据
        /// </summary>
        /// <param name="key">键</param>
        /// <returns></returns>
        public static string GetStringValue(string key)
        {
            if (string.IsNullOrEmpty(key))
            {
                return null;
            }
            try
            {
                return _csredis.Get(key);//_redisCache.GetString(key);
            }
            catch (Exception ex)
            {
                return null;
            }
        }

        public static  string GetCacheAsync(string key, Func<object> factory, int ExprireTime = 30)
        {
            string items = null;
            items = GetStringValue(key);
            if (items == null)
            {
                try
                {
                    items = JsonConvert.SerializeObject(factory());
                    SetStringValue(key, items, ExprireTime);
                    return items;
                }
                catch (Exception ex)
                {
                    return items;
                }
            }
            return items;
        }

        public static async Task<string> GetCacheAsync(string key, Func<Task<object>> factory, int ExprireTime = 30)
        {
            string items = null;
            items = GetStringValue(key);
            if (items == null)
            {
                try
                {
                    items = JsonConvert.SerializeObject(await factory());
                    SetStringValue(key, items, ExprireTime);
                    return items;
                }
                catch (Exception ex)
                {
                    return items;
                }
            }
            return items;
        }
        /// <summary>
        /// 移除数据
        /// </summary>
        /// <param name="key">键</param>
        public static bool Remove(string key)
        {
            if (string.IsNullOrEmpty(key))
            {
                return false;
            }
            try
            {
                if (Exists(key))
                {
                    _csredis.Del(key);//_redisCache.Remove(key);
                }
                return true;
            }
            catch (Exception ex)
            {
                return false;
            }
        }
        /// <summary>
        /// 刷新数据
        /// </summary>
        /// <param name="key">键</param>
        public static bool Refresh(string key)
        {
            if (string.IsNullOrEmpty(key))
            {
                return false;
            }
            try
            {
                //_redisCache.Refresh(key);
                return true;
            }
            catch (Exception ex)
            {
                return false;
            }
        }
        /// <summary>
        /// 重置数据
        /// </summary>
        /// <param name="key">键</param>
        /// <param name="value">值</param>
        /// <param name="expireTime">过期时间 单位小时</param>
        public static bool Replace(string key, string value, int expireTime = 1)
        {
            if (Remove(key))
            {
                return SetStringValue(key, value, expireTime);
            }
            else
            {
                return false;
            }
        }
        /// <summary>
        /// 验证是否存在
        /// </summary>
        /// <param name="key">键</param>
        /// <returns></returns>
        public static bool Exists(string key)
        {
            var cacheVal = _csredis.Get(key);
            if (cacheVal == null)
            {
                return false;
            }
            else
            {
                return true;
            }
        }
    }
}
